import React, { Component, PropTypes } from 'react';
import { Form, Icon, Input, Button, Checkbox, message } from 'antd';
import Md5 from 'js-md5';
import { connect } from 'dva'
import Style from './index.less';
import Service from '../service';

const FormItem = Form.Item;
var map, point, local;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      searchValue: '',
      adressList: []
    }
  }
  componentDidMount() {
    const token = localStorage.getItem('token');
    // this.props.queryStatistics({ token: token })
    // this.entityListFun();
    this.initMap();
  }
  componentWillUnmount() {
    let self = this;
    self.props.urlStatus({
      url: '/updatelocation'
    });
  }

  // 地图初始化
  initMap = () => {
    let self = this;
    var map = new BMap.Map("allmap");
    let latitude = localStorage.getItem('latitude');
    let longitude = localStorage.getItem('longitude');
    map.centerAndZoom(new BMap.Point(longitude, latitude), 11);

    var options = {
      onSearchComplete: function (results) {
        // console.log(results)
        // 判断状态是否正确
        let adressList = [];
        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
          var s = [];
          for (var i = 0; i < results.getCurrentNumPois(); i++) {
            adressList.push({
              title: results.getPoi(i).title,
              address: results.getPoi(i).address,
              point: results.getPoi(i).point,
            })
            s.push(results.getPoi(i).title + ", " + results.getPoi(i).address);
          }
          // console.log(adressList)
          self.setState({
            adressList: adressList
          })
          // document.getElementById("r-result").innerHTML = s.join("<br/>");
        }
      }
    };
    local = new BMap.LocalSearch(map, options);

  }
  getLocation() {
    //根据IP获取城市 
    var myCity = new BMap.LocalCity();
    myCity.get(getCityByIP);

    //获取GPS坐标 
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showMap, handleError, { enableHighAccuracy: true, maximumAge: 1000 });
    } else {
      alert("您的浏览器不支持使用HTML 5来获取地理位置服务");
    }
  }
  showMap(value) {
    var longitude = value.coords.longitude;
    var latitude = value.coords.latitude;
    map = new BMap.Map("mapWrap");
    x = latitude;
    y = longitude;
    //alert("坐标经度为：" + latitude + "， 纬度为：" + longitude ); 
    gpsPoint = new BMap.Point(longitude, latitude); // 创建点坐标 


    //根据坐标逆解析地址 
    var geoc = new BMap.Geocoder();
    geoc.getLocation(gpsPoint, getCityByCoordinate);

    BMap.Convertor.translate(gpsPoint, 0, translateCallback);
    map.enableScrollWheelZoom(true);
  }

  // 搜索
  searchConFun = (event) => {
    let v = event.target.value;
    this.setState({
      searchValue: v
    })
    local.search(v);
  }
  // 取消搜索
  clearSearchFun = () => {
    this.setState({
      searchValue: '',
      adressList: []
    })
  }
  // 返回
  returnFun = () => {
    this.context.router.push(`/uindex`);
  }
  //  查看详情
  detailFun = (record) => {
    let self = this;
    self.props.saveDetail(record);
    this.context.router.push(`/uindex`);
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { adressList } = this.state;
    return (
      <div className={Style.wrap}>
        <div id="allmap" style={{ display: 'none' }}></div>
        <div id="r-result"></div>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            <span className={Style.arrow} onClick={this.returnFun}>
              <Icon type="left" />
            </span>
            更改我的位置
            {/* <span className={Style.arrow + ' ' + Style.arrowText} onClick={this.handleSubmit}>提交</span> */}
          </div>
        </div>
        <div className={Style.dataWrap}>
          <div className={Style.searchWrapTitle}>
            <div className={Style.searchInput}>
              <span className={Style.searchIcon}>
                <Icon type="search" />
              </span>
              <input onChange={this.searchConFun} value={this.state.searchValue} />
              {this.state.searchValue &&
                <span className={Style.closeIcon} onClick={this.clearSearchFun}>
                  <Icon type="close-circle" />
                </span>
              }

            </div>

          </div>
          <div className={Style.searchWrap}>

            <div className={Style.searchList}>
              {/* adressList */}
              {adressList && adressList.map((item, index) => {
                return (
                  <dl onClick={this.detailFun.bind(this, item)}>
                    <dt>{item.title}</dt>
                    <dd>{item.address}</dd>
                  </dl>
                )
              })}
            </div>
          </div>
        </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  return {
    userMsg: state.login.userMsg,
    data: state.login.data.data
  }
}
function dispatchToProps(dispatch) {
  return {
    saveDetail(payload, params) {
      dispatch({
        type: 'umodel/saveDetail',
        payload
      })
    },
    urlStatus(payload, params) {
      dispatch({
        type: 'myHome/urlStatus',
        payload
      })
    }

  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
